//
//  OrderViewModel.swift
//  FeastBooking
//
//  Created by Imon on 2017/10/20.
//  Copyright © 2017年 Imon. All rights reserved.
//

import Foundation
import RxSwift
import Moya

class OrderViewModel {
    
    private var provider: RxMoyaProvider<OrderApi>
    
    init(token: String) {
        let endpointClosure = { (target: OrderApi) -> Endpoint<OrderApi> in
            let defaultEndpoint = RxMoyaProvider.defaultEndpointMapping(for: target)
            return defaultEndpoint.adding(newHTTPHeaderFields: ["content-type": "application/json", "Authorization": "Bearer \(token)"])
        }
        provider = RxMoyaProvider<OrderApi>(endpointClosure: endpointClosure)
    }
    
    func postOrder(order: OrderPost) -> Observable<PostResponse> {
        return provider.request(.postOrder(order: order))
               .mapJSON()
               .mapObject(type: PostResponse.self)
    }
    
    func getUserOrders(status: String, page: Int) -> Observable<UserOrdersResponse> {
        return provider.request(.getUserOrders(status: status, page: page))
               .mapJSON()
               .mapObject(type: UserOrdersResponse.self)
    }
    
    func getOrderDetail(id: Int) -> Observable<UserOrderDetail> {
        return provider.request(.getOrderDetail(id: id))
               .mapJSON()
               .mapObject(type: UserOrderDetail.self)
    }
    
    func updateManager(id: Int, username: String) -> Observable<PostResponse> {
        return provider.request(.updateOrderManager(id: id, manager: username))
               .mapJSON()
               .mapObject(type: PostResponse.self)
    }
    
    func updateFeastingDate(id: Int, date: String) -> Observable<String> {
        return provider.request(.updateFeastingDate(id: id, date: date))
               .mapString()
    }
    
    func postContract(id: Int, deleted: String, images: [UIImage]) -> Observable<String> {
        return provider.request(.postOrderContract(id: id, deleted: deleted, contract: images))
               .mapString()
    }
    
    func postPayment(id: Int, deleted: String, images: [UIImage], amountPaid: Double) -> Observable<String> {
        return provider.request(.postOrderPayment(id: id, amountPaid: amountPaid, deleted: deleted, payment: images))
               .mapString()
    }
    
    func postOrderReviews(id: Int, rating: Int, review: String) -> Observable<Any> {
        return provider.request(.postOrderReviews(id: id, rating: rating, review: review))
               .mapJSON()
    }
}
